package org.itboys.mobile.controller.web.information;

import com.wordnik.swagger.annotations.Api;
import org.apache.ibatis.annotations.Param;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mdl.entity.mongo.information.MdlPortalImage;
import org.itboys.mdl.entity.mongo.information.MdlPortalInfo;
import org.itboys.mobile.service.mongo.mobile.information.MdlPortalImageService;
import org.itboys.mobile.service.mongo.mobile.information.MdlPortalInfosService;
import org.itboys.mobile.service.mongo.mobile.information.MdlPortalItemsService;
import org.itboys.param.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2017/12/1.
 * @author 朱坤涛
 * 资讯管理
 */
@Controller
@RequestMapping("/Mdl/PortalInfos")
public class MdlPortalInfosController extends BaseController{

    @Autowired
    private MdlPortalItemsService portalItemsService;
    @Autowired
    private MdlPortalInfosService portalInfoService;
    @Autowired
    private MdlPortalImageService portalImageService;
    @Autowired
    private ResourceHolder resourceHolder;

    @RequestMapping("/toVM")
    public ModelAndView toVM(HttpServletResponse request, HttpServletResponse response) {
        return new ModelAndView("/portal/portal_info");
    }

    /**
     * 获取资讯栏目
     * @param itemId
     * @param request
     * @param response
     */
    @RequestMapping("/getByItemId/{itemId}")
    public void getByItemId(@PathVariable("itemId") Long itemId, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("itemId", itemId);
        PageResult<MdlPortalInfo> list = portalInfoService.pageQuery(request,param);
        JsonPageUtils.renderJsonPage(list.getTotal(), list.getData(), response);
    }

    @RequestMapping("/input")
    public ModelAndView input(@Param("itemId") Long itemId, @Param("id") Long id, HttpServletResponse response, org.springframework.ui.Model model) {
        if(id != null) {
            MdlPortalInfo info = portalInfoService.getById(id);
            model.addAttribute("info",info);
            model.addAttribute("item",portalItemsService.getById(info.getItemId()));
            if(info.getType() == 2) {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("portalId", info.getId());
                model.addAttribute("imageList",portalImageService.list(param));
            }
        } else {
            model.addAttribute("item",portalItemsService.getById(itemId));
        }
        model.addAttribute("staticRoot",resourceHolder.getStringValue("staticRoot"));
        model.addAttribute("adminRoot",resourceHolder.getStringValue("adminRoot"));
        model.addAttribute("imgRoot",resourceHolder.getStringValue("imgRoot"));
        return new ModelAndView("/portal/input");
    }

    /**
     * 增加或修改资讯信息
     * @param info
     * @param imageList
     * @param zhuImage
     * @param bigImage
     * @param request
     * @param response
     */
    @RequestMapping("/addPortalInfo")
    public void addPortalInfo(@ModelAttribute MdlPortalInfo info, @RequestParam("imageList") MultipartFile[] imageList, @RequestParam("zhuImage1") MultipartFile zhuImage, @RequestParam("bigImage1") MultipartFile bigImage, HttpServletRequest request, HttpServletResponse response) {
        try {
            String fileUploadPath = resourceHolder.getStringValue("fileUploadPath");
            List<MdlPortalImage> list = new ArrayList<MdlPortalImage>();
            if (imageList != null && imageList.length > 0) {
                for (MultipartFile file : imageList) {
                    if (file != null && !file.isEmpty()) {
                        String filePath = FileUtils.saveFile(file.getInputStream(), fileUploadPath, file.getOriginalFilename(), file.getContentType());
                        MdlPortalImage productImages = new MdlPortalImage();
                        productImages.setImage(filePath);
                        list.add(productImages);
                    }
                }
            }
            // 设置主图
            if(info.getType() == 1) {
                if (zhuImage != null && !zhuImage.isEmpty()) {
                    String filePath = FileUtils.saveFile(zhuImage.getInputStream(), fileUploadPath, zhuImage.getOriginalFilename(), zhuImage.getContentType());
                    info.setZhuImage(filePath);
                } else {
                    if(info.getId() == 0l) {
                        AjaxUtils.renderText(response, "-2");// 系统异常
                        return;
                    }
                }
            }
            // 设置大图
            if(info.getType() == 3) {
                if (bigImage != null && !bigImage.isEmpty()) {
                    String filePath = FileUtils.saveFile(bigImage.getInputStream(), fileUploadPath, bigImage.getOriginalFilename(), bigImage.getContentType());
                    info.setBigImage(filePath);
                } else {
                    if(info.getId() == 0l) {
                        AjaxUtils.renderText(response, "-3");// 系统异常
                        return;
                    }
                }
            }
            // 设置多图
            if(info.getType() == 2) {
                if(info.getId() == 0l) {
                    if (list == null || list.size() == 0) {
                        AjaxUtils.renderText(response, "-4");// 系统异常
                        return;
                    }
                }
            }
            portalInfoService.savaInfo(info, list);
        } catch (Exception e) {
            e.printStackTrace();
            AjaxUtils.renderText(response, "-1");// 系统异常
        }
    }

    @RequestMapping("/delete")
    public void delete(@RequestParam Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            portalInfoService.deleteInfo(id);
            AjaxUtils.renderText(response, "success");
        } catch (Exception e) {
            AjaxUtils.renderText(response, "fail");
        }
    }

    @RequestMapping("/deleteImage")
    public void deleteImage(@RequestParam Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            portalImageService.delete(id);
            AjaxUtils.renderText(response, "success");
        } catch (Exception e) {
            AjaxUtils.renderText(response, "fail");
        }
    }

    @RequestMapping("/top")
    public void top(@RequestParam Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("isTop", 1);
            List<MdlPortalInfo>  i = portalInfoService.list(param);
            if(i != null) {
                i.get(0).getIsTop();
                portalInfoService.updateExceptEmpty(i.get(0).getId(),i.get(0));
            }
            MdlPortalInfo info = portalInfoService.getById(id);
            info.setIsTop(1);
            portalInfoService.updateExceptEmpty(i.get(0).getId(),info);
            AjaxUtils.renderText(response, "success");
        } catch (Exception e) {
            AjaxUtils.renderText(response, "fail");
        }
    }
}
